﻿using Coldairarrow.Entity.MEGA;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.MEGA
{
    public class MEGA_XZQHBusiness : BaseBusiness<MEGA_XZQH>, IMEGA_XZQHBusiness, ITransientDependency
    {
        readonly IDbAccessor _Db;
        public MEGA_XZQHBusiness(IDbAccessor db, IDbAccessor Db)
            : base(db)
        {
            _Db = Db;
        }

        #region 外部接口

        public async Task<PageResult<MEGA_XZQH>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<MEGA_XZQH>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<MEGA_XZQH, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<MEGA_XZQH> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(MEGA_XZQH data)
        {
            string code = data.Code;
            string name = data.Name;
            var model = GetIQueryable().Where(x => x.Code.Equals(code) && x.Name.Equals(name)).FirstOrDefault();
            if (model != null)
            {
                throw new Exception("该区划已经存在!");
            }
            data.Code.Trim();
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(MEGA_XZQH data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<List<Base_DepartmentTreeDTO>> GetOneTreeDataListAsync(DepartmentsTreeInputDTO input)
        {
            var where = LinqHelper.True<MEGA_XZQH>();
            where = where.And(x => x.Level == 1);
            if (!string.IsNullOrWhiteSpace(input.parentId))
                where = where.And(x => x.ParentId == input.parentId);

            var list = await GetIQueryable().Where(where).ToListAsync();
            var treeList = list
                .Select(x => new Base_DepartmentTreeDTO
                {
                    Id = x.Id,
                    ParentId = x.ParentId,
                    Text = x.Name,
                    value = x.Id,
                    label = x.Name,
                    Lat = x.Lat,
                    Lng = x.Lng,
                    Code = x.Code

                }).ToList();

            return TreeHelper.BuildTreeTwo(treeList);
        }

        public async Task<List<Base_DepartmentTreeDTO>> GetAllTreeDataListAsync(DepartmentsTreeInputDTO input)
        {
            var where = LinqHelper.True<MEGA_XZQH>();
          
            if (!string.IsNullOrWhiteSpace(input.parentId))
                where = where.And(x => x.ParentId == input.parentId);

            var list = await GetIQueryable().Where(where).ToListAsync();
            var treeList = list
                .Select(x => new Base_DepartmentTreeDTO
                {
                    Id = x.Id,
                    ParentId = x.ParentId,
                    Text = x.Name,
                    label = x.Name,
                    value = x.Id,
                    Lat = x.Lat,
                    Lng = x.Lng,
                    Code = x.Code

                }).ToList();

            return TreeHelper.BuildTreeTwo(treeList);
        }

        public async Task<List<Base_DepartmentTreeDTO>> GetTwoTreeDataListAsync(DepartmentsTreeInputDTO input)
        {
            var where = LinqHelper.True<MEGA_XZQH>();
          
            if (!string.IsNullOrWhiteSpace(input.parentId))
                where = where.And(x => x.ParentId == input.parentId);

            var list = await GetIQueryable().Where(where).ToListAsync();
            var treeList = list
                .Select(x => new Base_DepartmentTreeDTO
                {
                    Id = x.Id,
                    ParentId = x.ParentId,
                    Text = x.Name,
                    label = x.Name,
                    value = x.Id,
                    Lat = x.Lat,
                    Lng = x.Lng,
                    Code = x.Code

                }).ToList();

            return TreeHelper.BuildTreeTwo(treeList);
        }

        public async Task<List<Base_DepartmentTreeDTO>> GetThreeTreeDataListAsync(DepartmentsTreeInputDTO input)
        {
            var where = LinqHelper.True<MEGA_XZQH>();
          
            if (!string.IsNullOrWhiteSpace(input.parentId))
                where = where.And(x => x.ParentId == input.parentId);

            var list = await GetIQueryable().Where(where).ToListAsync();
            var treeList = list
                .Select(x => new Base_DepartmentTreeDTO
                {
                    Id = x.Id,
                    ParentId = x.ParentId,
                    Text = x.Name,
                    label = x.Name,
                    value = x.Id,
                    Lat = x.Lat,
                    Lng = x.Lng,
                    Code = x.Code

                }).ToList();

            return TreeHelper.BuildTreeTwo(treeList);
        }

        public async Task<object> ExportToExcelData()
        {
            string[] rowNameList = new[] {"主键Id","区划名称","上级区划Id","区划编码","经度","纬度","区划等级" };
            string strExcelFileName = "行政区划表";
            var q = GetIQueryable();
            var dt = q.ToDataTable<MEGA_XZQH>().DefaultView.ToTable(false, new string[] { "Id", "Name", "ParentId", "Code", "Lng", "Lat", "Level" }); ;

            if (dt.Rows.Count==0)
            {
                throw new Exception("暂无数据");
            }
            else
            {
                ExportToExcel.datatableToExcel(dt, strExcelFileName, rowNameList);
            }

            var res = new
            {
                Success = true,
                States = 200
            };

            return  res.ToJson();
             
        }

        public List<string> GetChildrenIds(string departmentId)
        {
            var allNode = GetIQueryable().Select(x => new TreeModel
            {
                Id = x.Id,
                ParentId = x.ParentId,
                Text = x.Name,
                Value = x.Id
            }).ToList();

            var children = TreeHelper
                .GetChildren(allNode, allNode.Where(x => x.Id == departmentId).FirstOrDefault(), true)
                .Select(x => x.Id)
                .ToList();

            return children;
        }


        #endregion

        #region 私有成员

        #endregion
    }
}